/**
 * Luke Valenta
 * March 2013
 * Tutoring App
 * 
 * This was made to get practice uploading and downloading strings from AWS S3.
 */

package com.example.aws_s3_practice;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements S3Fragment.OnDownloadFinishedListener {
	
	private static final String TAG = "S3Fragment";
	private static final String KEY = "TextViewKey";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if(savedInstanceState != null) {
			String mString = savedInstanceState.getString(KEY);
			TextView mTextView = (TextView) this.findViewById(R.id.text_view);
			mTextView.setText(mString);
		}

		S3Fragment frag;
		FragmentManager manager = getFragmentManager();
		if(manager.findFragmentByTag(TAG) == null) {
			FragmentTransaction transaction = manager.beginTransaction();
			frag = new S3Fragment();
			transaction.add(frag, TAG).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		
		TextView mTextView = (TextView) this.findViewById(R.id.text_view);
		String mString = mTextView.getText().toString();
		savedInstanceState.putString(KEY, mString);
	}

	public void onUpload(View v) {
		S3Fragment mS3Frag = (S3Fragment) 
				getFragmentManager().findFragmentByTag(TAG);
		EditText mEditText = (EditText) this.findViewById(R.id.edit_text);
		String mString = mEditText.getText().toString();
		mS3Frag.uploadToBucket(mString, getString(R.string.string_key), getString(R.string.bucket_name));	
	}
	
	public void onDownload(View v) {
		S3Fragment mS3Frag = (S3Fragment) 
				getFragmentManager().findFragmentByTag(TAG);
		mS3Frag.downloadFromBucket(getString(R.string.string_key), getString(R.string.bucket_name));
	}
	
	public void onDownloadFinished(String result) {
		TextView mTextView = (TextView) this.findViewById(R.id.text_view);
		mTextView.setText(result);
	}
}
